package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.baomidou.mybatisplus.annotation.TableLogic;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author 李俊伟
 * @date 2024/12/25 11:56
 */
// token JWT工具类
public class JwtUtil {
    // 设置token到期时间 1个小时
    private static long tokenExpiration = 60 * 60 * 1000L;
    // 密钥
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("c0cc0dfdfaef2370e4d56711175fe349def6ed4cba25d3c7a01fc6ef6568220d".getBytes());

    // 后端创建一个token携带登录用户的信息
    public static String createToken(Long userId,String username){
        String token = Jwts.builder()
                .setSubject("SystemUser-token")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId).claim("username", username)
                .signWith(tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    // 验证前端传入的token
    public static Claims parseToken(String token) {
        Claims body = null;
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(tokenSignKey).build().parseClaimsJws(token);
            body = claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }

//// 测试 创建token 和 验证token
//    public static void main(String[] args) throws InterruptedException {
//        String token = createToken(1l, "lijunwei");
////        System.out.println("token创建成功 ：" + token);
////        Thread.sleep(2000);
//        Claims claims = parseToken(token);
//        System.out.println(claims.get("userId"));
//        System.out.println(claims.get("username"));
//    }

}